
#include <BRender>
#include <BPainter>
#include <BScene>
#include <BShape>
#include <BViewer>

#include "MainHandler.h"

MainHandler::MainHandler()
{
	_frustumPoints = new BVectorArray(8);
	_enableLights = new BLightArray();
	_visualNodes = new BNodeArray();
	_shapeQueue = new BMap<BShape*, BBox>();
	_transShapeQueue = new BMap<BShape*, BBox>();
}
MainHandler::~MainHandler()
{

}

void MainHandler::setTargetCamera(BCamera* camera)
{
	_camera = camera;
	if (_camera)
	{
		connect(_camera, Signal_Dirty, &MainHandler::slotCameraDirty);
		connect(_camera, Signal_Fresh, &MainHandler::slotCameraDirty);
	}
}

void MainHandler::slotCameraDirty()
{
	this->fresh();
}

void MainHandler::paint(BPainter& painter)
{
	BString text("visual node size : ");
	text += _visualNodes->size();
	text << "\nvisual shape count : ";
	text << _shapeQueue->size();

	painter.setColor(BColor(255, 255, 0));
	painter.drawText(this->viewer()->clientRect(), text);
}

void MainHandler::render(BRender& render)
{
	_camera->query("frustum", _frustumPoints);
	_camera->query("lights", _enableLights);
	_camera->query("shapes", _shapeQueue);
	_camera->query("transShapes", _transShapeQueue);

	BScene* scene = this->scene();
	if (_camera && scene)
	{
		render.setLighting(false);
		render.setCullBack(false);
		for (auto it = _shapeQueue->begin(); it.valid(); it++)
		{
			BShape* shape = it.key();
			render.drawBox(it.value());
		}
		render.setColor(0, 255, 255);
		for (auto it = _transShapeQueue->begin(); it.valid(); it++)
		{
			BShape* shape = it.key();
			render.drawBox(it.value());
		}

		BVector pos = _camera->position();
		BVector center = _camera->center();

		render.setColor(255, 0, 255);
		render.setLineWidth(3);
		render.drawLine(pos, center);

		BVector* vs = _frustumPoints->data();
		render.setColor(255, 0, 0, 200);
		render.fillQuad(vs[0], vs[1], vs[2], vs[3]);
		render.fillQuad(vs[4], vs[5], vs[6], vs[7]);
		render.setColor(255, 255, 0, 200);
		render.fillQuad(vs[0], vs[1], vs[5], vs[4]);
		render.fillQuad(vs[2], vs[3], vs[7], vs[6]);
		render.setColor(0, 255, 255, 200);
		render.fillQuad(vs[1], vs[2], vs[6], vs[5]);
		render.fillQuad(vs[0], vs[3], vs[7], vs[4]);
	}

}


